package com.blank.web.listener;

import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class MyListener implements ServletRequestListener {
    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {

    }

    @Override
    public void requestInitialized(ServletRequestEvent servletRequestEvent) {
       HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequestEvent.getServletRequest();
        HttpSession session = httpServletRequest.getSession();
        if (null == session.getAttribute("user")){
            //如果没有登录则从cookie中获取登录信息
            Cookie[] cookies = httpServletRequest.getCookies();
            //遍历cookies
            if(cookies != null){
                for (Cookie cookie :cookies){
                    if("user".equalsIgnoreCase(cookie.getName())){
                        //如果成功找到就保存到session中
                        session.setAttribute("user",cookie.getValue());
                        System.out.println("成功从cookie中传入信息到session");
                    }
                }
            }
        }
    }
}
